//
//  HResetPassWordViewController.m
//  Router
//
//  Created by Zhen Huang on 2018/6/20.
//  Copyright © 2018年 James. All rights reserved.
//

#import "HResetPassWordViewController.h"
#import "HHomeViewController.h"
#import "AppDelegate.h"
@interface HResetPassWordViewController ()
<UITextFieldDelegate>
@property (nonatomic, strong)UITextField *mobileText;
@property (nonatomic, strong)UITextField *codeText;
@property (nonatomic, strong)UITextField *passWordText;
@property (nonatomic, strong)UITextField *makesurePassWordText;
@property (nonatomic, strong)UIButton *LoginButton;
@property (nonatomic, strong)UIButton *authCodeBtn;//获取验证码
@end

@implementation HResetPassWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kBackGroundColor;
    [self.view addSubview:self.mobileText];
    [self.view addSubview:self.codeText];
    [self.view addSubview:self.passWordText];
    [self.view addSubview:self.makesurePassWordText];
    [self.view addSubview:self.LoginButton];
    [self.view addSubview:self.authCodeBtn];
    [self createUserCodeAndPassWord];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(UITextFieldTextDidChangeEditingNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
}
//监听textfield代理
- (void)UITextFieldTextDidChangeEditingNotification:(NSNotification *)noti {
    UITextField *textField = noti.object;
    if (textField.tag == 110) {
        self.mobileText.text = textField.text;
    }else if (textField.tag == 120) {
        self.codeText.text = textField.text;
    }else if (textField.tag == 130) {
        self.passWordText.text = textField.text;
    }else if (textField.tag == 140) {
        self.makesurePassWordText.text = textField.text;
    }
}
- (UITextField *)mobileText {
    if (!_mobileText) {
        _mobileText = [[UITextField alloc]initWithFrame:CGRectMake(20, ScreenHeight / 2 - 56 * 2 - 15.5 - 25, ScreenWidth - 200, 25)];
        _mobileText.delegate = self;
        _mobileText.placeholder = @"手机号";
        _mobileText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_mobileText.placeholder attributes:@{NSForegroundColorAttributeName: [Networking colorWithHexString:@"#455A6A"]}];
        _mobileText.textColor = kTitleBackGroundColor;
        _mobileText.tag = 110;
    }
    return _mobileText;
}
- (UITextField *)codeText {
    if (!_codeText) {
        _codeText = [[UITextField alloc]initWithFrame:CGRectMake(20, ScreenHeight / 2 - 56  - 15.5 - 25, ScreenWidth - 200, 25)];
        _codeText.delegate = self;
        _codeText.placeholder = @"请输入验证码";
        _codeText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_codeText.placeholder attributes:@{NSForegroundColorAttributeName: [Networking colorWithHexString:@"#455A6A"]}];
        _codeText.textColor = kTitleBackGroundColor;
        _codeText.tag = 120;
    }
    return _codeText;
}
- (UITextField *)passWordText {
    if (!_passWordText) {
        _passWordText = [[UITextField alloc]initWithFrame:CGRectMake(20, ScreenHeight / 2  - 15.5 - 25, ScreenWidth - 200, 25)];
        _passWordText.delegate = self;
        _passWordText.placeholder = @"请输入密码";
        _passWordText.tag = 130;
        _passWordText.textColor = kTitleBackGroundColor;
        _passWordText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_passWordText.placeholder attributes:@{NSForegroundColorAttributeName: [Networking colorWithHexString:@"#455A6A"]}];
    }
    return _passWordText;
}
- (UITextField *)makesurePassWordText {
    if (!_makesurePassWordText) {
        _makesurePassWordText = [[UITextField alloc]initWithFrame:CGRectMake(20,ScreenHeight / 2 +  56 - 15.5 - 25, ScreenWidth - 200, 25)];
        _makesurePassWordText.delegate = self;
        _makesurePassWordText.placeholder = @"确认密码";
        _makesurePassWordText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:_makesurePassWordText.placeholder attributes:@{NSForegroundColorAttributeName: [Networking colorWithHexString:@"#455A6A"]}];
        _makesurePassWordText.textColor = kTitleBackGroundColor;
        _makesurePassWordText.tag = 140;
    }
    return _makesurePassWordText;
}
- (UIButton *)LoginButton {
    if (!_LoginButton) {
        _LoginButton = [[UIButton alloc]initWithFrame:CGRectMake(28,ScreenHeight - 150,ScreenWidth - 56,55)];
        _LoginButton.layer.masksToBounds = YES;
        _LoginButton.layer.cornerRadius = 25;
        if (iPhone5) {
            _LoginButton.height = 40;
            _LoginButton.layer.cornerRadius = 20;
        }
        _LoginButton.titleLabel.font = [UIFont fontWithName:PingFangSCRegular size:16];
        _LoginButton.backgroundColor = kNavBlueColor;
        [_LoginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_LoginButton setTitle:@"立即登录" forState:UIControlStateNormal];
        [[_LoginButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
            NSString *url = F(@"%@/users/reset_password", BaseUrl);
            NSDictionary *paramDic = @{@"mobile":self.mobileText.text?:@"",
                                       @"code":self.codeText.text?:@"",
                                       @"password":self.passWordText.text?:@""};
            NSString *param = [self dictionaryToJson:paramDic];
            [self receivePOSTWithTokenURLString:url method:@"POST" body:param Token:nil Blocks:^(NSDictionary *tempData, NSInteger state) {
                if (tempData) {
                    [[TMCache sharedCache]setObject:[tempData objectForKey:@"token"] forKey:@"Token"];
                    [[TMCache sharedCache]setObject:[[tempData objectForKey:@"user"]objectForKey:@"username"] forKey:@"UserName"];
                    AppDelegate *app = (AppDelegate *)[[UIApplication  sharedApplication] delegate];
                    [app rootViewToTabBar];
                }
            }];
        }];
    }
    return _LoginButton;
}
- (void)createUserCodeAndPassWord {
    for (int i = 0; i < 4; i ++) {
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, ScreenHeight / 2 - 56 - 56 + 56 *i, ScreenWidth - 40, 1)];
        lineView.backgroundColor = [Networking colorWithHexString:@"#455A6A"];
        [self.view addSubview:lineView];
    }
}
- (UIButton *)authCodeBtn {
    if (!_authCodeBtn) {
        _authCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _authCodeBtn.frame = CGRectMake(ScreenWidth - 20 - 130,self.codeText.top - 6,130, 40);
        [_authCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _authCodeBtn.layer.borderColor = [kNavBlueColor CGColor];
        _authCodeBtn.layer.borderWidth = 1.0f;
        _authCodeBtn.layer.masksToBounds = YES;
        _authCodeBtn.layer.cornerRadius = 20;
        [_authCodeBtn setTitleColor:kNavBlueColor forState:UIControlStateNormal];
        _authCodeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        _authCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        [[_authCodeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
            if (self.mobileText.text.length == 0 || ![[self.mobileText.text substringToIndex:1] isEqualToString:@"1"] || self.mobileText.text.length < 11) {
                [self alert:@"请输入正确的手机号!"];
            }else {
                [self openCountdown];
                //获取验证码
                NSString *url = F(@"%@/sms",BaseUrl);
                NSDictionary *paramDic = @{@"mobile":self.mobileText.text?:@"",
                                           @"send_type":@"forget"};
                NSString *param = [self dictionaryToJson:paramDic];
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [self receivePOSTWithTokenURLString:url method:@"POST" body:param Token:nil Blocks:^(NSDictionary *tempData, NSInteger state) {
                                                     
                    }];
                });
            }
        }];
    }
    return _authCodeBtn;
}
//设置获取验证码倒计时
-(void)openCountdown{
    __block NSInteger time = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.authCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.authCodeBtn setTitleColor:kNavBlueColor forState:UIControlStateNormal];
                self.authCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.authCodeBtn setTitle:[NSString stringWithFormat:@"已发送%.2ds", seconds] forState:UIControlStateNormal];
                [self.authCodeBtn setTitleColor:[Networking colorWithHexString:@"#979797"] forState:UIControlStateNormal];
                self.authCodeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}
//点击界面的任意地方，回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
